package com.ican.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ican.common.SystemConstants;
import com.opensymphony.xwork2.ActionContext;

public class ContextUtils {
    
    private final static Logger logger = LoggerFactory.getLogger(ContextUtils.class);
	    
	public static Map<String, Object> getSessionMap(){
		return ActionContext.getContext().getSession();
	}
	
	public static HttpSession getSession(){
		return ServletActionContext.getRequest().getSession();
	}
	
	public static HttpServletRequest getRequest(){
		return ServletActionContext.getRequest();
	}
	
	public static HttpServletResponse getResponse(){
		return ServletActionContext.getResponse();
	}
	
	public static WebApplicationContext getSpringContext(){
		return WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
	}
	
	public static Object getBeanFromSpringContext(String beanName){
		return getSpringContext().getBean(beanName);
	}
	
	public static String getservletRealPath(){
		return ServletActionContext.getServletContext().getRealPath("\\");
	}
	
	public static String getContextPath(){
        return ServletActionContext.getServletContext().getContextPath();
    }
	
	public static void write2Response(String content){      
        HttpServletResponse response = ServletActionContext.getResponse();      
        response.setCharacterEncoding("UTF-8");
        try{
            response.getWriter().write(content);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
        }
    }
	
	public static void errorMsg2Session(String msg){
	    if(msg == null){
	        getSessionMap().put(SystemConstants.KEY_ERROR_MSG, SystemConstants.MSG_ERROR_DEFAULT);
	    }else{
	        getSessionMap().put(SystemConstants.KEY_ERROR_MSG, msg);
	    }
    }
	
	public static void successMsg2Session(String msg){
	    if(msg == null){
            getSessionMap().put(SystemConstants.KEY_SUCCESS_MSG, SystemConstants.MSG_SUCCESS_DEFAULT);
        }else{
            getSessionMap().put(SystemConstants.KEY_SUCCESS_MSG, msg);
        }
    }
}
